package com.example.controller;

import java.security.Principal;

import com.example.dao.WebSocketMessage;
import com.example.dao.WebSocketResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class WsController {

	@MessageMapping("/welcome")//请求地址
	@SendTo("/topic/getResponse")//订阅消息地址，客户端通过这个地址订阅，订阅后服务端会向其发送消息
	public WebSocketResponse say(WebSocketMessage message) throws Exception {
		Thread.sleep(3000);
		return new WebSocketResponse("Welcome, " + message.getName() + "!");
	}

	@Autowired
	private SimpMessagingTemplate messagingTemplate;//1

	@MessageMapping("/chat")
	public void handleChat(Principal principal, String msg) { //2
		if (principal.getName().equals("wyf")) {//3
			messagingTemplate.convertAndSendToUser("wisely",
					"/queue/notifications", principal.getName() + "-send:"
							+ msg);
		} else {
			messagingTemplate.convertAndSendToUser("wyf",
					"/queue/notifications", principal.getName() + "-send:"
							+ msg);
		}
	}
}